<?php

/**
 * Msa_PrestationObject - Classe de gestion des prestations
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Msa_PrestationObject extends Erra_Fields_Base_Object {

    function __construct($objectId, $buildArgs = null) {
        parent::__construct($objectId, $buildArgs);
        $name = Erra_Fields_Text::create('prestation_name')
                ->setDescription('Nom de la prestation *')
                ->setHelp('Entrez le nom de la prestation')
                ->setInAdminList(true)
                ->setDatabaseType('VARCHAR', 256)
                ->setSize(70);

        $internet_name = Erra_Fields_Text::create('internet_name')
                ->setDatabaseType('VARCHAR', 64)
                ->setDescription('Nom sur Internet');

        $agendaTree = Msa_AgendaObject::getAuthorizedAgendaTree();
        $assignation = Erra_Fields_Tree::create('assignation')
                ->setDescription('Assigner aux agendas')
                ->setDatabaseType('TEXT')
                ->fill($agendaTree);

        $sqlPrestationList = Msa_TypeprestationObject::getPrestationSQLList();
        ksort($sqlPrestationList);
        $prestation_type_id = Erra_Fields_ComboBox::create('prestation_type_id')
                ->setDatabaseType('INT', 16)
                ->setDescription('Type de prestation')
                ->setInAdminList(true)
                ->fill($sqlPrestationList);


        $slot_color = Erra_Fields_Color::create('slot_color')
                ->setDatabaseType('VARCHAR', 16)
                ->setInAdminList(true)
                ->setDescription('Couleur de la prestation');

        $duree = Erra_Fields_Text::create('duree')
                ->setInAdminList(true)
                ->setDatabaseType('VARCHAR', 8)
                ->setDescription('Durée *(en minutes)');

        $prix = Erra_Fields_Text::create('prix')
                ->setInAdminList(true)
                ->setDatabaseType('VARCHAR', 8)
                ->setDescription('Prix *(en euros, ex: 19.90)');

        $search = $name->createTextSearch();
        $search->addAttribute('class', 'erra-form-agenda-search-input')
                ->setOperator('LIKE %?%')
                ->setDescription('Rechercher par nom de prestation');

        $description_interne = Erra_Fields_TextArea::create('description_courte_interne')
                ->setCols(60)
                ->setRows(2)
                ->setDescription('Description interne de la prestation')
                ->setDatabaseType('VARCHAR', 256);

        $description_courte = Erra_Fields_TextArea::create('description_courte_prestation')
                ->setCols(60)
                ->setRows(2)
                ->setDescription('Courte description de la prestation (pour Internet)')
                ->setDatabaseType('VARCHAR', 256);

        $description = Erra_Fields_TextArea::create('description_prestation')
                ->setCols(70)
                ->setDescription('Description longue de la prestation');

        $image_prestation = Erra_Fields_ImageBank::create('image_prestation')
                ->setDir('image_banks/prestation')
                ->setHeight(125)
                ->setDatabaseType('VARCHAR', 256)
                ->setDescription('Image prestation');

        $display_price = Erra_Fields_ComboBox::create('display_price')
                ->setDatabaseType('TINYINT', 4)
                ->setDescription('Afficher le prix pour mes clients')
                ->fill(array(1 => 'Oui', 0 => 'Non'));

        $this->addFields($name, $display_price, $internet_name, $assignation, $prestation_type_id, $duree, $prix, $description_interne, $description_courte, $description, $slot_color, $image_prestation, $search);

        Msa_ExtraPrestationFieldObject::addExtraFields($this);
        $this->addExtraFieldsIds();
        $this->setDescription('Ajouter / Modifier une prestation');
        $this->setAddText('Cliquez ici pour ajouter une prestation');
    }

    /**
     * getPrestationTree() - Retourne un arbre contenant la liste complete des prestations
     * 
     * @return type
     */
    public static function getPrestationTree() {
        // FIXME : optimize algorithm ? (with 2 requests)
        $resultArray = array();
        $prestations = Erra_Core_DatabasePdo::SELECT('SELECT msa_prestationobject.id, prestation_name, prestation_type_name, prestation_type_id FROM msa_prestationobject, msa_typeprestationobject WHERE msa_typeprestationobject.id = msa_prestationobject.prestation_type_id AND msa_prestationobject.id  != 0');
        $prestationsList = array();
        $categories = array();
        if (is_object($prestations)) {
            while ($row = $prestations->fetch()) {
                $prestationsList[] = $row;
                if (!isset($categories[$row->prestation_type_id])) {
                    $categories[$row->prestation_type_id] = $row->prestation_type_name;
                }
            }
            if (count($categories)) {
                foreach ($categories as $categoryId => $categoryName) {
                    // On classe l'arbre par catégories
                    $categoryArray = array();
                    $categoryArray['title'] = $categoryName;
                    $categoryArray['key'] = $categoryId;
                    foreach ($prestationsList as $prestation) {
                        if ($categoryId == $prestation->prestation_type_id) {
                            if (!isset($categoryArray['children'])) {
                                $categoryArray['children'] = array();
                            }
                            // Si la catégorie n'est pas celle par défaut, on ajoute la prestation à la prestation
                            if ($categoryId > 0) {
                                $categoryArray['children'][] = array('title' => $prestation->prestation_name, 'key' => $prestation->id);
                            } else {
                                $resultArray[] = array('title' => $prestation->prestation_name, 'key' => $prestation->id);
                            }
                        }
                    }
                    if ($categoryId > 0) {
                        $resultArray[] = $categoryArray;
                    }
                }
            }
        }

        return array('title' => 'Prestations', 'key' => 'root',
            'expand' => true, 'children' => $resultArray);
    }

    /**
     * getPrestationTreeFromAgendaId() - Retourne un arbre des prestations autorisés pour un agenda particulier
     * 
     * @param type $agendaId
     * @return type
     */
    public static function getPrestationTreeFromAgendaId($agendaId = null) {
        $resultArray = array();
        // D'abord on récupere toutes les catégories
        $categoriesList = array();
        $categorieSql = Erra_Core_DatabasePdo::SELECT('SELECT msa_typeprestationobject.id, prestation_type_name FROM msa_typeprestationobject');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $categorieSql->fetch()) {
                $categoriesList[$row->id] = $row->prestation_type_name;
            }
        }
        $categoriesList[0] = 'Autres';
        // On récupere les données pour les prestations
        $prestationsList = array();
        if ($agendaId == null) {
            $prestationSql = Erra_Core_DatabasePdo::SELECT('SELECT msa_prestationobject.id, prestation_name, prestation_type_id FROM msa_prestationobject');
        } else if (is_numeric($agendaId)) {
            $prestationSql = Erra_Core_DatabasePdo::SELECT('SELECT msa_prestationobject.id, prestation_name, prestation_type_id FROM msa_prestationobject WHERE msa_prestationobject.id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id=' . $agendaId . ')');
        }
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $prestationSql->fetch()) {
                $prestationsList[] = $row;
            }
        }
        $alreadyAddedPrestations = array();
        if (count($categoriesList)) {
            foreach ($categoriesList as $categoryId => $categoryName) {
                // On classe l'arbre par catégories
                $categoryArray = array();
                $categoryArray['title'] = $categoryName;
                $categoryArray['key'] = $categoryId;
                foreach ($prestationsList as $prestation) {
                    if ($categoryId == $prestation->prestation_type_id) {
                        if (!isset($categoryArray['children'])) {
                            $categoryArray['children'] = array();
                        }
                        // Si la catégorie n'est pas celle par défaut, on ajoute la prestation à la prestation
                        if ($categoryId > 0) {
                            // If parent category has children, it's value is null
                            $categoryArray['key'] = 'null';
                            $categoryArray['children'][] = array('title' => $prestation->prestation_name, 'key' => $prestation->id);
                            $alreadyAddedPrestations[] = $prestation->id;
                        }
                    }
                }
                if ($categoryId > 0 && count($categoryArray['children'])) {
                    $resultArray[] = $categoryArray;
                }
            }
        }
        // On ajoute les prestations orphelines (sans catégories parent)
        foreach ($prestationsList as $prestation) {
            if (!in_array($prestation->id, $alreadyAddedPrestations)) {
                $resultArray[] = array('title' => $prestation->prestation_name, 'key' => $prestation->id);
            }
        }
        return array(array('title' => 'Prestations',
                'key' => 'root', 'children' => $resultArray));
    }

    /**
     * getPrestationInfos() - Retourne un tableau associatif avec la liste des prestations et les information essentielles
     * 
     * @return type
     */
    public static function getPrestationInfos() {
        $resultArray = array();
        $prestations = Erra_Core_DatabasePdo::SELECT('SELECT id, prestation_name, internet_name, duree, slot_color, prix FROM msa_prestationobject');
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $prestations->fetch()) {
                $resultArray[$row->id] = array('duree' => $row->duree, 'color' => $row->slot_color, 'name' => $row->prestation_name);
            }
        }
        return $resultArray;
    }

    /**
     * getPrestationListFromAgendaId() - Retourne un tableau associatif avec la liste des prestations et les information essentielles, en fonction d'un agenda
     * 
     * @param type $agendaId
     * @return type
     */
    public static function getPrestationListFromAgendaId($agendaId) {
        $resultArray = array();

        if (is_numeric($agendaId)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT id, prestation_name, internet_name, duree, slot_color, prix FROM msa_prestationobject WHERE id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id=' . $agendaId . ')');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $prestations->fetch()) {
                    $resultArray[] = $row;
                }
            }
        } else if (is_array($agendaId)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT id, prestation_name, internet_name, duree, slot_color, prix FROM msa_prestationobject WHERE id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id IN' . implode(',', $agendaId) . ')');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $prestations->fetch()) {
                    $resultArray[] = $row;
                }
            }
        }
        return $resultArray;
    }

    /**
     * getPrestationListFromAgendaId() - Retourne un tableau avec les id des prestations autorisées pour un agenda
     * 
     * @param type $agendaId
     * @return type
     */
    public static function getPrestationListIdFromAgendaId($agendaId) {
        $resultArray = array();

        if (is_numeric($agendaId)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT id  FROM msa_prestationobject WHERE id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id=' . $agendaId . ')');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $prestations->fetch()) {
                    $resultArray[] = $row->id;
                }
            }
        } else if (is_array($agendaId)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT id FROM msa_prestationobject WHERE id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id IN' . implode(',', $agendaId) . ')');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($row = $prestations->fetch()) {
                    $resultArray[] = $row->id;
                }
            }
        }
        return $resultArray;
    }

    /**
     * getPrestationListFromShopId() - Retourne la liste des prestations pour un magasin particulier (en se basant sur les agendas asosciés)
     * 
     * @param type $shop_id
     * @return type
     */
    public static function getPrestationListFromShopId($shop_id) {
        $resultArray = array();

        if (is_numeric($shop_id)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_prestationobject WHERE id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id IN(SELECT id FROM msa_agendaobject WHERE location=' . $shop_id . '))');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($prestation = $prestations->fetch()) {
                    $resultArray[] = $prestation;
                }
            }
        }
        return $resultArray;
    }

    /**
     * getPrestationListFromShopIdAndTypeId() - Retourne la liste des prestations pour un magasin en fonction dudit type de la prestation
     * 
     * @param type $shop_id
     * @param type $type_id
     * @return type
     */
    public static function getPrestationListFromShopIdAndTypeId($shop_id, $type_id) {
        $resultArray = array();

        if (is_numeric($shop_id) && is_numeric($type_id)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_prestationobject WHERE prestation_type_id=' . $type_id . ' AND id IN (SELECT prestation_id FROM back_agenda_prestation WHERE agenda_id IN(SELECT id FROM msa_agendaobject WHERE location=' . $shop_id . '))');
            if (Erra_Core_DatabasePdo::rowCount()) {
                while ($prestation = $prestations->fetch()) {
                    $resultArray[] = $prestation;
                }
            }
        }
        return $resultArray;
    }

    /**
     * getPrestationFromId() - Retourne les informations sur une prestation en se basant sur son id
     * 
     * @param type $id
     * @return type
     */
    public static function getPrestationFromId($id) {
        $result = array();

        if (is_numeric($id)) {
            $prestations = Erra_Core_DatabasePdo::SELECT('SELECT * FROM msa_prestationobject WHERE id=' . $id);
            if (Erra_Core_DatabasePdo::rowCount()) {
                $result = $prestations->fetch();
            }
        }
        return $result;
    }

    /**
     * postInit - Rempli la liste des des agendas auxquel est assignée cette prestation
     */
    public function postInit() {
        // Retreive agendas
        $resultArray = array();
        $agendas = Erra_Core_DatabasePdo::SELECT('SELECT agenda_id FROM back_agenda_prestation WHERE prestation_id=' . $this->getId());
        if (Erra_Core_DatabasePdo::rowCount()) {
            while ($row = $agendas->fetch()) {
                $resultArray[] = $row->agenda_id;
            }
        }
        $this->assignation->setRawData($resultArray);
    }

    /**
     * postListInit() - La prestation avec l'id 0 est utilisé en interne pour assurer l'integrité de la base, elle ne eput être supprimée
     */
    function postListInit() {
        $list = $this->getObjectDataArray();

        foreach ($list as $key => $item) {
            if ($item['id'] == 0) {
                unset($list[$key]);
            }
            if (isset($item['slot_color'])) {
                $list[$key]['slot_color'] = $this->buildColorPicker($list[$key]['slot_color'], $item['id']);
            }
        }
        if (is_numeric(Erra_Fields_Search_PageNumber::$realItemCount['Msa_PrestationObject'])) {
            Erra_Fields_Search_PageNumber::$realItemCount['Msa_PrestationObject'] -= 1;
        }
        $this->setObjectDataArray($list);
    }

    function buildColorPicker($selected_color, $cur_id) {
        //return "<div id='$id' style='border:1px solid;margin:auto; width:25px; height:25px; background:#$selected_color' ></div>";
        return "<div  style='text-align:center;'>"
                .$this->slot_color->makeAjaxColorEditor($selected_color, 
                        array(
                            'onchange-function'=>'ajaxPrestationColorChange', 
                            'id'=>$cur_id)).
                '</div>';
    }

    /**
     * addExtraFieldsIds() - Par défaut, les champs supplémentaires sont en hidden, on les assigne plus tard avec ExtraPrestationFieldObject
     */
    function addExtraFieldsIds() {
        // Get data
        for ($i = 1; $i <= 5; $i++) {
            if ($this->getSubFieldAt('extra_field_' . $i) == null) {
                $extra_field = Erra_Fields_Hidden::create('extra_field_' . $i);
                $this->addField($extra_field);
            }
        }
    }

}

?>